package com.dragon.connector.imServer.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.dragon.connector.imServer.cocurrent.FutureTaskScheduler;
import com.dragon.connector.imServer.serverProcesser.ReceiveMessageProcesser;
import com.dragon.connector.imServer.session.LocalSession;
import com.dragon.protoJo.bean.msg.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ReceiveMessageHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg == null && !(msg instanceof ProtoMsg.Message)){
            super.channelRead(ctx,msg);
            return;
        }

        ProtoMsg.Message message = (ProtoMsg.Message) msg;

        ProtoMsg.HeadType headType = message.getType();

        ReceiveMessageProcesser receiveMessageProcesser = SpringUtil.getBean(ReceiveMessageProcesser.class);

        if(!headType.equals(receiveMessageProcesser.op())){
            super.channelRead(ctx,msg);
            return;
        }

        // 异步处理接收聊天消息
        FutureTaskScheduler.add(()->{
//            LocalSession session = LocalSession.getSession(ctx);
//            // 判断该用户是否已经登录了的，如果登录了，则直接发送消息，如果没登录，则不发送任何消息
//            if(session != null && session.isLogin()){
//
//                return;
//            }
            receiveMessageProcesser.actionTcp(ctx,message);
            // 没有登录，则不发送消息
            //没有登录，则为中转消息,netty集群
//            ProtoMsg.MessageRequest request = message.getMessageRequest();
//            List<ServerSession> toSessions = SessionManger.inst().getSessionsBy(request.getTo());
//            toSessions.forEach((serverSession) ->
//            {
//                if (serverSession instanceof LocalSession)
//                // 将IM消息发送到接收方
//                {
//                    serverSession.writeAndFlush(message);
//                }
//            });
        });
    }
}
